package com.kindnesslibrary.util;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.provider.MediaStore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 本地照片帮助类
 */
public class AlbumHelper {

    // 缩略图列表
    HashMap<String, String> thumbnailList = new HashMap<String, String>();
    // 专辑列表
    HashMap<String, Map<String, Object>> bucketList = new HashMap<String, Map<String, Object>>();

    private static AlbumHelper instance;
    private Context context;

    /**
     * 是否创建了图片集
     */
    boolean hasBuildImagesBucketList = false;

    private AlbumHelper() {
    }

    public static AlbumHelper getInstance() {
        if (instance == null) {
            instance = new AlbumHelper();
        }
        return instance;
    }

    /**
     * 初始化
     *
     * @param context
     */
    public void init(Context context) {
        if (this.context == null) {
            this.context = context;
        }
    }

    /**
     * 得到缩略图
     */
    private void getThumbnail() {
        String[] projection = {BaseColumns._ID, MediaStore.Images.Thumbnails.IMAGE_ID,
                MediaStore.Images.Thumbnails.DATA};
        ContentResolver cr = context.getContentResolver();
        Cursor cursor = cr.query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection,
                null, null, null);
        getThumbnailColumnData(cursor); // 从数据库中得到缩略图
        cr = null;
    }

    /**
     * 从数据库中得到缩略图
     * @param cur
     */
    private void getThumbnailColumnData(Cursor cur) {
        try {
            if (cur.moveToFirst()) {
                int image_idColumn = cur.getColumnIndex(MediaStore.Images.Thumbnails.IMAGE_ID);
                int dataColumn = cur.getColumnIndex(MediaStore.Images.Thumbnails.DATA);
                do {
                    int image_id = cur.getInt(image_idColumn);
                    String image_path = cur.getString(dataColumn);
                    thumbnailList.put("" + image_id, image_path);
                } while (cur.moveToNext());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cur.close();
        }
    }
    /**
     * 得到图片集
     */
    void buildImagesBucketList() {
        // 构造缩略图索引
        getThumbnail();
        Cursor cur = null;
        try {
            // 构造相册索引
            String columns[] = new String[]{BaseColumns._ID, MediaStore.Images.ImageColumns.BUCKET_ID,
                    MediaStore.Images.ImageColumns.PICASA_ID, MediaStore.MediaColumns.DATA,
                    MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.SIZE,
                    MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME};
            ContentResolver cr = context.getContentResolver();
            // 得到一个游标
            cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
                    null, null);
            cr = null;
            // 获取指定列的索引
            int photoIDIndex = cur.getColumnIndexOrThrow(BaseColumns._ID);
            int photoPathIndex = cur.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
            int bucketIdIndex = cur.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.BUCKET_ID);
            int bucketDisplayNameIndex = cur.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME);
            if (cur.moveToLast()) {
                do {
                    String _id = cur.getString(photoIDIndex);
                    String path = cur.getString(photoPathIndex);
                    String bucketId = cur.getString(bucketIdIndex);
                    String bucketName = cur.getString(bucketDisplayNameIndex);
                    Map<String, Object> bucket = bucketList.get(bucketId);
                    if (bucket == null) {
                        bucket = new HashMap<>();
                        bucketList.put(bucketId, bucket);
                        ArrayList<Map<String, Object>> imageList = new ArrayList<Map<String, Object>>();
                        bucket.put("imageList", imageList);
                        bucket.put("bucketName", bucketName);
                    }
                    if (bucket.get("count") == null) {
                        bucket.put("count", 0);
                    }
                    int count = (int)bucket.get("count");
                    bucket.put("count", ++count);
                    Map<String, Object> imageItem = new HashMap<>();
                    imageItem.put("imageId", _id);
                    imageItem.put("imagePath", path);
                    imageItem.put("thumbnailPath", thumbnailList.get(_id));
                    // 图片列表
                    if (bucket.get("imageList") == null) {
                        List<Map<String, Object>> item = new ArrayList<Map<String, Object>>();
                        bucket.put("imageList", item);
                    }
                    ((List<Map<String, Object>>) bucket.get("imageList"))
                            .add(imageItem);
                }while(cur.moveToPrevious());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(cur != null){
                cur.close();
            }
        }
        hasBuildImagesBucketList = true; // 图片缓存成功，下次就不用再缓存，读取速率会加快
    }

    /**
     *
     * @return
     */
    public ArrayList<Map<String, Object>> getImagesBucketList() {
        if(!hasBuildImagesBucketList){
            buildImagesBucketList();
        }
        ArrayList<Map<String, Object>> tmpList = new ArrayList<Map<String, Object>>();
        for(Map.Entry<String, Map<String, Object>> entry : bucketList.entrySet()){
            tmpList.add(entry.getValue());
        }
        return tmpList;
    }

}
